import {getTradeInfo,getUserAddress,submitOrder,getPayInfo,getOrderList} from "api/api"
import router from "router/router"
import {Message} from "element-ui"
export default {
    state:{
        tradeInfo:{},
        userAddress:[],
        orderId:'',
        payInfo:{},
        orderInfo:{}
    },
    getters:{},
    mutations:{
        getOrderList(state,orderInfo){
            state.orderInfo=orderInfo
        },
        getTradeInfo(state,tradeInfo){
            state.tradeInfo=tradeInfo
        },
        getUserAddress(state,userAddress){
            state.userAddress=userAddress
        },
        submitOrder(state,orderId){
            state.orderId=orderId
        },
        getPayInfo(state,payInfo){
            state.payInfo=payInfo
        }
    },
    actions:{
        //获取订单列表
        async getOrderList(store,{pageNo,pageSize}) {
            const {code, data} = await getOrderList(pageNo,pageSize)
            if (code === 200) {
                store.commit("getOrderList", data)
            }
            return code
        },
        //获取交易信息
        async getTradeInfo(store) {
            const {code, data} = await getTradeInfo()
            if (code === 200) {
                store.commit("getTradeInfo", data)
            }
            return code
        },
        //获取用户地址
        async getUserAddress(store){
            const {code, data} = await getUserAddress()
            if (code === 200) {
                store.commit("getUserAddress", data)
            }
            return code
        },
        //提交订单 data:{consignee:收件人姓名,consigneeTel:收件人电话....}
        async submitOrder(store,{tradeNo,data}){
            try {
                const {code,data:orderId,message} = await submitOrder(tradeNo,data);
                if(code === 200){
                    store.commit("submitOrder",orderId);
                    //跳转到支付界面
                    await router.push(`/pay?orderId=${orderId}`);
                }else{
                    //错误提醒
                    Message.error(message)
                }
                return code
            }catch (err){
                Message.error(err.message);
                return 400;
            }
        },
        //获取支付信息
        async getPayInfo(store,orderId){
            try {
                const {code,data} = await getPayInfo(orderId);
                if(code === 200){
                    store.commit("getPayInfo",data);
                    //成功...
                }else{
                    //失败.....
                }
                return {code,data}
            }catch (error){
                    //异常......
                return {code:400,error}
            }
        }
    }
}